<?php
	class Migration_1_1_2 extends GigaMigration
	{
		function migrate($migrateShell)
		{
			$this->fixRatings($migrateShell);
			$this->schemaChanges($migrateShell);
			$this->fixRatingsAvg($migrateShell);
			$this->fixCustomFieldOptions();
		}
    
    /**
     *
     * Fixes two bugs.
     * 1. removes rating label from rating field name.
     * 2. Move this field to float table.
     * @param type $migrateShell
     * @return type 
     */
    private function fixRatings($migrateShell)
    {
        App::import("Model","Eav.EavValue");
        $EavInt = new EavValuesInt();
        $EavFloat = new EavValuesFloat();
        $ratingFieldConditions = array(
            "field like" =>"rateablefield_%"
        );
        $recordCount = $EavInt->find("count",array("conditions"=>$ratingFieldConditions));
        if(!$recordCount)
        {
            return;
        }
        $limit = 10;
        $migrateShell->out("Fixing rating values. Hold on this could take some time");
        $migrateShell->out("Found $recordCount records");
        $pages = $recordCount/$limit;
        if($pages < 1)
        {
            $pages = 1;
        }else
        {
            $pages = ceil($pages);
        }
        for($page=$pages;$page > 0;$page--)
        {
            $ratingRecords =  $EavInt->find("all",array("conditions"=>$ratingFieldConditions,"limit"=>$limit,"page"=>$page));
            $savedIds = array();
            foreach($ratingRecords as $ratingRecord)
            {
                $saveValue = $this->fixAndMoveRating($EavFloat,$ratingRecord[$EavInt->alias]);
                if($saveValue)
                {
                    $savedIds[] = $ratingRecord[$EavInt->alias]['id'];
                }
            }
            $EavInt->deleteAll(array("id"=>$savedIds));
        }
    }
    private function fixAndMoveRating(EavValuesFloat $EavFloat,$ratingRecord)
    {
        require_once(MODELS.'rateable_field.php'); 
		App::import("Model","RateableField");

        //$RatingModel = cri("RateableField");   // strangely this model is not registered in App class so loading directly
        $RatingModel =new RateableField;

        $originalFieldName = $ratingRecord['field'];
        $ratingFieldId = array_pop(explode("_",$originalFieldName));
        $newFieldName = $RatingModel->customFieldName($ratingFieldId);
        $newRecord = $ratingRecord;
        $newRecord['field'] = $newFieldName;
        unset($newRecord['id']);
        $EavFloat->create();
        $EavFloat->save(array($EavFloat->alias => $newRecord),array("callbacks"=>false));
        return true;
    }
	
	function fixRatingsAvg($migrateShell)
	{
		$ListingModel = cri("Listing");
		$listings = $ListingModel->find("list",array("callbacks"=>false,"fields"=>array("id"),"conditions"=>array("review_count >"=>0,"or"=>array("userAvg"=>0,"userAvg is null"))));
		foreach($listings as $listingId)
		{
			$ListingModel->saveRatingAverages($listingId);
		}
	}
	
	function fixCustomFieldOptions()
	{
		ClassRegistry::flush();
		$CustomFieldModel = cri("CustomField");
		$CustomFieldOptionModel = cri("CustomFieldOption");
		$customFields = cri("CustomField")->find("all",array("conditions"=>array(
			"type" => array("multipleSelect","select","checkbox","multipleCheckbox","radio")
		)));
		foreach($customFields as $customField)
		{
			$CustomFieldModel->create();
			if($CustomFieldOptionModel->hasAny(array("custom_field_id"=>$customField['CustomField']['id'])))
			{
				continue;
			}
			foreach($customField['CustomField']['options'] as $key => $option)
			{
				$customField['CustomField']['options'][$key] = array(
					"field_value" => $option,
					"key" => $key
				);
				
			}
			unset($customField['CustomFieldOption']);
			if($CustomFieldModel->saveAll($customField))
			{
				$CustomFieldModel->_processFieldOptionsAfterSave($customField['CustomField']['id']);
			}
		}
	}
	
	private function schemaChanges()
	{
		cri("Listing")->query("ALTER TABLE  `newsletters` ADD  `newsletter_type` VARCHAR( 30 ) NOT NULL");
		cri("Listing")->query("ALTER TABLE  `plans` ADD  `allow_multiple_categories` INT NOT NULL DEFAULT '1'");
		cri("Listing")->query("ALTER TABLE  `plans` ADD  `limit_events` SMALLINT NOT NULL");
		cri("Listing")->query("ALTER TABLE  `plans` ADD  `allowed_events_limit` INT NOT NULL");
		cri("Listing")->query("ALTER TABLE  `plans` ADD  `enable_deals` SMALLINT NOT NULL");
		cri("Listing")->query("ALTER TABLE  `plans` ADD  `active_deals_limit` INT NOT NULL");
		cri("Listing")->query("ALTER TABLE  `content_scopes` ADD  `randomize` INT NOT NULL");
		cri("Listing")->query("ALTER TABLE  `languages` ADD  `is_default` INT NOT NULL");
		cri("Listing")->query("ALTER TABLE  `listings` ADD  `category_list` TEXT NOT NULL");
		
		//don't remove this debug statement. Suprreses a sql error.
		Configure::write("debug",0);
			//we can also comment/remove the alter table statements for deals, deal_orders and custom_field_options
			//because these are new tables and following statements will show sql errors for already existing column
			cri("Listing")->query("ALTER TABLE  `deals` ADD  `activated` INT NOT NULL DEFAULT '0'");
			cri("Listing")->query("ALTER TABLE  `custom_field_options` ADD  `key` INT NOT NULL DEFAULT '0'");
			cri("Listing")->query("ALTER TABLE  `deal_orders` ADD  `tax_rate` FLOAT NOT NULL");
		
			cri("Listing")->query("ALTER TABLE	`listings`  DROP INDEX `is_featured`");
			cri("Listing")->query('ALTER TABLE	`listings` ADD INDEX  `is_featured` (  `is_featured` )');
			cri("Listing")->query('ALTER TABLE	`reviews` ADD INDEX listing_id_2 (`listing_id`, `status`)');
		Configure::write("debug",1);
	}
}
?>